let g = 9.8 // 重力加速度
let bounce = 0.85 // 弹性碰撞后速度的损失系数
let eps = 1e-7

class Player extends GameObject {
    // 构造函数
    constructor(playground, id, p, v, radius, img) {
        super()
        this.id = id
        this.playground = playground
        this.ctx = playground.ctx
        this.p = {
            x: p.x,
            y: p.y,
        }
        this.v = {
            x: v.x,
            y: v.y,
        }
        this.a = {
            x: 0,
            y: g,
        }
        this.radius = radius
        this.img = new Image()
        this.img.src = img
        super.start()
    }

    render() {
        let ctx = this.playground.ctx
        ctx.drawImage(this.img, this.p.x, this.p.y, this.radius, this.radius)
    }

    update() {
        this.v.y += this.a.y * this.timeDelta / 40
        this.p.y += this.v.y * this.timeDelta / 40
        this.v.x += this.a.x * this.timeDelta / 40
        this.p.x += this.v.x * this.timeDelta / 40
        this.checkEdgeCollision()
        this.checkCollisionWithOthers()
        this.render()
    }

    checkCollisionWithOthers() {
        let players = this.playground.players
        for (let i = 0; i < players.length; i++) {
            let player = players[i]
            if (player.id === this.id) {
                continue
            }
            console.log(this.distance(player.p))
            if (this.distance(player.p) <= this.radius + player.radius) {
                let tmp = this.v
                this.v = player.v
                player.v = tmp
            }
        }
    }

    distance(p) {
        let dx = this.p.x - p.x
        let dy = this.p.y - p.y
        return Math.sqrt(dx * dx + dy * dy)
    }

    checkEdgeCollision() {
        if (this.p.y >= this.ctx.height - this.radius) {
            this.v.y = -this.v.y * bounce
            this.p.y = this.ctx.height - this.radius
            if (this.v.y < eps) {
                this.v.x *= 0.98
            }
        }
        if (this.p.x >= this.ctx.width - this.radius) {
            this.v.x = -this.v.x * bounce
            this.p.x = this.ctx.width - this.radius
        }
        if (this.p.x <= this.radius) {
            this.v.x = -this.v.x * bounce
            this.p.x = this.radius
        }
    }
}
